
function aptReleaseInit() {
    var userHasRights = false;
    var tagList = [];
    emosWS.addEventListener("UserRight", function(msg) {
        // Check if users have right to release devices: 
        if (AptCheckUserRight("Release")) {
            userHasRights = true;
        } else {
            userHasRights = false;
        }
        userRightsChanged(userHasRights);
    });

    var advisedId = emosWS.getNewElementId();
    var tableSelector = "apt_ReleaseTableContainer";
    var appName = sessionStorage.getItem("apt_appName");
    var robotData;
    var languageTexts = {
        "T02_releaseHeatingControl": {
            id: "apt_ReleaseHeatingHeader",
            text: "Release Heating"
        },
        "T02_ReleaseHeatingsHeader": {
            id: "apt_ReleaseHeatingAllHeader",
            text: "Heatings"
        }
    };

    $.ajax({
        url: '../../../apps/' + appName + '/global/releaseHeating.JSON',
        type: 'post',
        dataType: 'json',
        async: true,
        cache: false,
        success: function(data) {
            createDom(data);
            robotData = data;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            AptWriteLog("[APT Error] Could not read " + '../../../apps/' + appName + '/global/releaseHeating.JSON' + ". Error: " + errorThrown + "", "error");
        }
    });

    function createDom(data) {
        console.log(data)
        var robots = Object.keys(data);
        var robotPositions = {};

        var min = [];
        var max = [];

        robots.forEach(function(robName) {
            var options = data[robName]; 
            
            var positionx = parseInt(options.X);
            var positiony = parseInt(options.Y);

            robotPositions[robName] = {
                x: positionx,
                y: positiony
            };

            if (min.length === 0) min = [positionx, positiony];
            if (max.length === 0) max = [positionx, positiony];

            if (positionx <= min[0]) min[0] = positionx;
            else if (positionx >= max[0]) max[0] = positionx;

            if (positiony <= min[1]) min[1] = positiony;
            else if (positiony >= max[1]) max[1] = positiony;
        });

        createDynamicTable(min, max, tableSelector, "robotReleaseTable", "robotReleaseTableCell");
        var handlerObj = [];

        var opc = sessionStorage.getItem("apt_PLC.OpcTopic");
        var appName = sessionStorage.getItem("apt_appName");

        for (var rob in data) {
            console.log(rob)
            var options = data[rob];
            var x = robotPositions[rob].x;
            var y = robotPositions[rob].y;

            var html = "<div class='robReleaseWindow '>";
            html += "<table><td>" + rob + "</td>";

            var robnr = sessionStorage.getItem("apt_" + rob + ".RobNr");

            if (options.heating.count > 0) {
              for (var i = 0; i < options.heating.count; i++) {
                var id = getElementGlobalID();
                var overlayId = getElementGlobalID();
                var innerId = getElementGlobalID();
                html += "<td><div id='" + id + "' class='emosbutton releaseButton releaseHeating disabled'><div id = '" + overlayId + "' class='innerImageDiv'><div id = '" + innerId + "' class='innerImageDiv'></div></div></div><h4>" + options.heating.no[i] + "</h4></td>";
                
                var num = i + 1;
                var releaseHeatingTag = appName + ".IO_HmiPVC.PVC[" + options.Index + "].Heating[" + num + "].mRelease";
                var enableHeatingTag = appName + ".IO_HmiPVC.PVC[" + options.Index + "].Heating[" + num + "].mEnable";
                var heatingStateTag = appName + ".IO_HmiPVC.PVC[" + options.Index + "].Heating[" + num + "].mState";
                

                tagList.push(enableHeatingTag)

                handlerObj.push({
                    tag: releaseHeatingTag,
                    id: overlayId,
                    function: function(tag, id) { handleRelease(tag, id); }
                });
                handlerObj.push({
                    tag: enableHeatingTag,
                    id: id,
                    function: function(tag, id) { handleToggleClick(tag, id); }
                });
                handlerObj.push({
                    tag: heatingStateTag,
                    id: id,
                    function: function(tag, id) { handleButtonState(tag, id); }
                });                                                            
              }   
            }

            html += "</table></div>";
            placeHtmlInTable(html, x, y, tableSelector);
        }

        // Execute all functions for all buttons
        handlerObj.forEach(function(obj) {
            obj.function(obj.tag, obj.id);
        });
        tagList.forEach(element => {
            console.log("**:" + element)
        });
        

    }

    function handleRelease(tag, id) {
        emosWS.advise(tag, function(msg) {
            console.log(msg.value)
            if (msg.value != true) {
                $('#' + id).addClass("unreleased");
            } else {
                $('#' + id).removeClass("unreleased");
            }
        }).setId(advisedId);
    }

    function handleToggleClick(tag, id) {
        $('#' + id).click(function() {
            emosWS.poke(tag, +!GetTagValueAsBoolean(tag));
            console.log(tag);
        });
    }

    function handleButtonState(tag, id) {
        emosWS.advise(tag, function(msg) {
            var element = $('#' + id);
            switch (msg.value) {
                case "1":
                    handleButtonStateCss(element, "green");
                    break;
                case "0":
                    handleButtonStateCss(element, "grey");
                    break;
                default:
                    handleButtonStateCss(element, "grey");
            }
        }).setId(advisedId);
    }

    function handleButtonStateCss(element, addedColor) {
        var cssClasses = $(element).attr('class').split(/\s+/)
        for (var i = 0; i < cssClasses.length; i++) {
            if (cssClasses[i].startsWith("state")) {
                element.removeClass(cssClasses[i]);
            }
        }
        element.addClass("state" + addedColor);
    }

    function releaseAllHeatings(state) {
        tagList.forEach(e => {
            // console.log(e)
            var value = 0;
            if (state) value = 1;
            emosWS.poke(e, value);
        });  
    }

    function userRightsChanged() {
        if (userHasRights) {
            $('.emosbutton').removeClass("disabled");
        } else {
            $('.emosbutton').addClass("disabled");
        }
    }

    function eventHandler() {
        $('#apt_ReleaseContainer').on("remove", function() {
            emosWS.unadvise(advisedId);
        });

        $('#racHeatingOnButton').click(function() {
            releaseAllHeatings(true);
        });

        $('#racHeatingOffButton').click(function() {
            releaseAllHeatings(false);
        });

        $('body').click(function() {
            if (!userHasRights) {
                if ($('#login').length === 0) $('#login', parent.document).trigger('click');
                else $('#login').trigger('click');
            }
        });
    }

    languageHandler(languageTexts);
    eventHandler();
}


function initReleaseWindow() {
    emosWS.connect({ onopen: aptReleaseInit() });
}